<?php
declare (strict_types = 1);

namespace app\middleware;
use think\Response;
use think\Request;
use think\facade\Db;

/**
 * 用户中间件
 */

use think\facade\View;

class CheckZbdUser
{
    /**
     *  用户中间件
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $param = $request->param();
        if (isset($param['s'])) {
            unset($param['s']);
        }

        # 用户登录的全局session 对象
        
        // $arr = array(
        //     'id' => '1',
        //     'type' => 'qq',
        //     'name' => '郑炳东',
        //     'nickname' => '郑炳东',
        //     'avatar' => 'http://qzapp.qlogo.cn/qzapp/101495803/BC5DE90D802DC1AD75940144073A1EED/100',
        // );

        // session('zbdInfo', $arr);
        
        $userInfo = session('zbdInfo') ? session('zbdInfo') : [];


        list($thisModule, $thisController, $thisAction) = [app('http')->getName(), $request->controller(), $request->action()];
        
         # 返回全局参数
        View::assign([
            'userInfo'        => $userInfo,
            'thisAction'      => $thisAction,
            'thisController'  => $thisController,
            'toDayDate'       => date('Y 年 m 月 d 日')
        ]);
        
        # 下面需要登录后才能操作
        if(in_array($thisController, ['User','AjaxSyn'])){

            if(!$userInfo && $request->isAjax()){
                return error('请先登录');
            }

            if(!$userInfo){
                return redirect('/login');
            }
        }

        $request->userId = isset($userInfo['id']) ? $userInfo['id'] : '';

        # 记录请求日志
        if(!in_array(getRealIp(), ['0.0.0.0', '127.0.0.1', '10.10.20.8'])){
            $Logs = [
                'user_id'     => isset($userInfo['id']) ? $userInfo['id'] : 0,
                'url'         => $request->url(),
                'method'      => strtolower($request->method()),
                'ip'          => getRealIp(),
                'content'     => json_encode($param, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                'useragent'   => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-',
                'create_time' => time(),
                'create_date' => date('Y-m-d H:i:s'),
            ];

            Db::table('ea_behavior_log')->insert($Logs);
        }

        # 判断是否为手机访问
        if($request->isMobile()){
            return redirect('/site.html');
        }
        
        $request->userInfo = $userInfo;
        
        return $next($request);
    }
}
